package com.qding.park.adapter.ark.adapter.impl;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.qding.park.adapter.ark.adapter.config.ARKConfig;
import com.qding.park.adapter.ark.adapter.constant.MethodConstant;
import com.qding.park.adapter.ark.adapter.entity.ResponseMsg;
import com.qding.park.adapter.ark.adapter.enums.LockEventEnum;
import com.qding.park.adapter.ark.adapter.enums.RespCodeEnums;
import com.qding.park.adapter.ark.adapter.util.Helper;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.system.NetWorkException;
import com.qding.park.common.core.network.HttpUtil;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.manager.pojo.ap.ApMonthFeeOrder;
import com.qding.park.target.common.adapter.PayFeeAdapter;
import com.qding.park.target.common.entity.AdMonthFeeOrder;
import com.qding.park.target.common.entity.AdTempPayOrder;
import com.qding.park.target.common.entity.AdTempPayResult;

@Service("payFeeAdapter_13")
public class PayFeeAdapterImpl implements PayFeeAdapter {

    private static final Logger _log = LoggerFactory.getLogger(PayFeeAdapterImpl.class);

    /*
     * (非 Javadoc) Description:临停费用查询
     * @see com.qding.park.target.common.adapter.PayFeeAdapter#createTempPayment(java.lang.String, java.lang.String)
     */
    @Override
    public AdTempPayOrder createTempPayment(String parkCode, String carNum, String userId)
            throws NetWorkException, AdapterException {
        String url = ARKConfig.getAdapterUrl();
        String urlMethod=Helper.createUrlAddress(url, MethodConstant.GET_TEMPORARY_PARKING_FEE);

        Map<String, String> params = new HashMap<String, String>();
        params.put("parkId", parkCode);
        params.put("carNo", carNum);
        params.put("personId", userId);
        try {
            String result = HttpUtil.doPost(urlMethod, params);
            ResponseMsg response = Helper.analysisResponse(result);

            if (!RespCodeEnums.SUCCESS.getValue().equals(response.getCode())) {
                // 失败
                ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                        AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), response.getMsg(),
                        "parkCode:" + parkCode + ",carNum:" + carNum + ",userId:" + userId);

                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        exceptionMessage);
            }

            JSONObject datajson = (JSONObject) response.getData();
            String orderId = datajson.getString("orderId");// 订单号
            String inParkTime = datajson.getString("inParkTime");// 入场时间格式： yyyy-MM-dd HH:mi:ss
            String parkingDuration = datajson.getString("parkingDuration");// 停车时长 单位秒
            String receivable = datajson.getString("receivable");// 应付金额 单位分
            String payFreeTime = datajson.getString("payFreeTime");// 支付后免费时长 单位秒
            AdTempPayOrder adTempPayOrder = new AdTempPayOrder();
            adTempPayOrder.setOrderId(orderId);
            adTempPayOrder.setEnterTime(DateUtils.parseDate(inParkTime, DateUtils.DATE_FORMAT_DATETIME));
            adTempPayOrder.setParkingTime(Integer.valueOf(parkingDuration));
            adTempPayOrder.setPayValue(Integer.valueOf(receivable));
            adTempPayOrder.setPayFreeTime(Integer.valueOf(payFreeTime));
            return adTempPayOrder;
        } catch (NetWorkException | IOException e) {
            _log.error(e.getMessage(), e);
            ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                    AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), "方舟接口调用异常",
                    "parkCode:" + parkCode + ",carNum:" + carNum + ",userId:" + userId);

            throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                    exceptionMessage);
        }
    }

    @Override
    public AdMonthFeeOrder calMonthFee(String parkId, int monthNum, String carNum)
            throws NetWorkException, AdapterException {
//        AdMonthFeeOrder ark = new AdMonthFeeOrder();
//        ark.setTotalFee(100000);
//        return ark;
        ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), "方舟月租费用计算接口暂时不支持",
                "方舟月租费用计算接口暂时不支持");
        throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null, exceptionMessage);
    }

    /*
     * (非 Javadoc) Description:临停车支付成功通知
     * @see com.qding.park.target.common.adapter.PayFeeAdapter#tempPaySuccessNotice(com.qding.park.target.common.entity.
     * AdTempPayOrder)
     */
    @Override
    public void tempPaySuccessNotice(AdTempPayResult adTempPayResult) throws NetWorkException, AdapterException {
        String url = ARKConfig.getAdapterUrl();
        String urlMethod=Helper.createUrlAddress(url, MethodConstant.PARK_PAY_RESULT);
        String orderId = adTempPayResult.getOrderId();
        String parkId = adTempPayResult.getParkCode();
        String projectId = adTempPayResult.getProjectId();
        String payTime = DateUtils.formatDate(adTempPayResult.getPayTime(), DateUtils.DATE_FORMAT_DATETIME);
        String realAmount = String.valueOf(adTempPayResult.getRealAmount());
        String receivable = String.valueOf(adTempPayResult.getShouldAmount());

        Map<String, String> params = new HashMap<String, String>();
        params.put("orderId", orderId);
        params.put("parkId", parkId);
        params.put("projectId", projectId);
        params.put("payTime", payTime);
        params.put("realAmount", realAmount);
        params.put("receivable", receivable);
        try {
            String result = HttpUtil.doPost(urlMethod, params);
            ResponseMsg response = Helper.analysisResponse(result);

            if (!RespCodeEnums.SUCCESS.getValue().equals(response.getCode())) {
                // 失败
                ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                        AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), response.getMsg(),
                        adTempPayResult.toString());

                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        exceptionMessage);
            }

        } catch (NetWorkException | IOException e) {
            _log.error(e.getMessage(), e);
            ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                    AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), "方舟接口调用异常", adTempPayResult.toString());

            throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                    exceptionMessage);
        }
    }

    @Override
    public AdMonthFeeOrder monthPay(String parkId, String carNum, int monthNum, int amount, Date payDate,
            String chargePaidNo) throws NetWorkException, AdapterException {
        ExceptionMessage exceptionMessage = ExceptionMessage.createExceptionMessage(
                AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), "方舟月租缴费接口暂时不支持",
                "方舟月租缴费接口暂时不支持");
        throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null, exceptionMessage);
    }

}
